package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoGifBinding;
import flc.ast.utils.Content;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoGifActivity extends BaseAc<ActivityVideoGifBinding> {

    public static String sVideoPath;
    private long videoLength;
    private int mFrame = 10;
    private float mSpeed = 1.0f;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.tvPlayLeft.setText(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), getString(R.string.duration_style)));
                mDataBinding.sbVideoPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            }
            mHandler.postDelayed(mTaskUpdateTime, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_gif;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoGifBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvVideoGifSave.setOnClickListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.tvFrame1.setOnClickListener(this);
        mDataBinding.tvFrame2.setOnClickListener(this);
        mDataBinding.tvFrame3.setOnClickListener(this);

        final String[] playSpeeds = getResources().getStringArray(R.array.ve_play_speed);
        int speedPos = (int) ((1f * mDataBinding.isbSpeed.getProgress()) / mDataBinding.isbSpeed.getMax() * (mDataBinding.isbSpeed.getTickCount() - 1));
        updateSpeed(playSpeeds[speedPos]);
        mDataBinding.isbSpeed.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                String selSpeed = playSpeeds[seekParams.thumbPosition];
                updateSpeed(selSpeed);
            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvVideoGifSave://导出
                save();
                break;
            case R.id.ivPlayStart://视频播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.aztsp);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.aabf);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvFrame1://5帧
                clearSelection();
                mDataBinding.tvFrame1.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvFrame1.setBackgroundColor(Color.parseColor("#1C5DFF"));
                mFrame = Integer.parseInt(mDataBinding.tvFrame1.getText().toString());
                mDataBinding.tvFrameTip.setText(getString(R.string.interval_num, mDataBinding.tvFrame1.getText().toString()));
                break;
            case R.id.tvFrame2://10帧
                clearSelection();
                mDataBinding.tvFrame2.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvFrame2.setBackgroundColor(Color.parseColor("#1C5DFF"));
                mFrame = Integer.parseInt(mDataBinding.tvFrame2.getText().toString());
                mDataBinding.tvFrameTip.setText(getString(R.string.interval_num, mDataBinding.tvFrame2.getText().toString()));
                break;
            case R.id.tvFrame3://15帧
                clearSelection();
                mDataBinding.tvFrame3.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvFrame3.setBackgroundColor(Color.parseColor("#1C5DFF"));
                mFrame = Integer.parseInt(mDataBinding.tvFrame3.getText().toString());
                mDataBinding.tvFrameTip.setText(getString(R.string.interval_num, mDataBinding.tvFrame3.getText().toString()));
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvFrameTip.setText(getString(R.string.interval_num, mDataBinding.tvFrame2.getText().toString()));
        videoLength = MediaUtil.getDuration(sVideoPath);
        setPlayer();
    }

    private void save() {
        int scaleWidth = mDataBinding.videoView.getWidth();
        int scaleHeight = mDataBinding.videoView.getHeight();
        if (scaleWidth * scaleHeight > 960 * 540) {
            //原视频分辨率过大，则要缩小一倍
            scaleWidth = scaleWidth / 2;
            scaleHeight = scaleHeight / 2;
        }
        showDialog(getString(R.string.ve_handle_percent_format, 0 + "%"));
        EditorHolder.editor().video2Gif(sVideoPath, scaleWidth, scaleHeight, mFrame, mSpeed, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                FileP2pUtil.copyPrivateImgToPublic(mContext, outFilePath);
                startActivity(HomeActivity.class);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.ve_covert_gif_fail_tip));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.ve_handle_percent_format, progress + "%"));
            }
        });
    }

    private void updateSpeed(String speedValue) {
        try {
            mSpeed = Float.parseFloat(speedValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideoPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.videoView.setVideoPath(sVideoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.aztsp);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.sbVideoPlay.setProgress(0);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.aabf);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.aabf);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    private void clearSelection() {
        mDataBinding.tvFrame1.setTextColor(Color.parseColor("#757171"));
        mDataBinding.tvFrame1.setBackgroundColor(Color.parseColor("#E0E0E0"));
        mDataBinding.tvFrame2.setTextColor(Color.parseColor("#757171"));
        mDataBinding.tvFrame2.setBackgroundColor(Color.parseColor("#E0E0E0"));
        mDataBinding.tvFrame3.setTextColor(Color.parseColor("#757171"));
        mDataBinding.tvFrame3.setBackgroundColor(Color.parseColor("#E0E0E0"));
    }

}